<template>
  <div class="online-tests-and-interviews" style="width: 100%;height: 100%">
    <h1 class="page-title">在线测试与面试</h1>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="参加面试" name="onlineTests">
        <el-table :data="onlineTests" class="activity-table" border>
          <el-table-column prop="job_title" label="职位名称" width="200"></el-table-column>
          <el-table-column prop="job_description" label="职位要求"></el-table-column>
          <el-table-column prop="applied_at" label="创建日期" width="180"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="primary" @click="takeTest(scope.row)">参加测试</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="结果查看" name="results">
        <el-table :data="results" class="activity-table" border>
          <el-table-column prop="job_title" label="职位名称" width="200"></el-table-column>
          <el-table-column prop="application_status" label="状态">
            <template slot-scope="scope">
            {{application_statusWacth(scope.row)}}
            </template>
          </el-table-column>
          <el-table-column prop="applied_at" label="日期" width="180"></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'OnlineTestsAndInterviews',
  data() {
    return {
      activeTab: 'onlineTests',
      onlineTests: [],
      results: [],
      allApplications: [],
      allJobs: [],
      loading: false,
      user:JSON.parse(localStorage.getItem('userData')) || {},
      studentId: null // 添加 studentId 属性
    };
  },
  created() {
    this.studentId = localStorage.getItem('student_id'); // 从 localStorage 获取 student_id
    if (this.studentId) {
      this.fetchData();
    } else {
      this.$message.error('未找到学生ID，请重新登录');
      this.$router.push('/login1'); // 跳转到登录页面
    }
  },
  watch: {
    activeTab(newTab) {
      if (newTab === 'results') {
        this.loadResultsData();
      }
    }
  },
  methods: {
    application_statusWacth(row){
      if (row.application_status==='shortlisted'){
        return '已入围';
      }else{
        if (row.application_status==='interviewed'){
          return '已面试';
        }
        if (row.application_status==='accepted'){
          return '已录用';
        }
        if (row.application_status==='rejected'){
          return '拒绝录用';
        }
        if (row.application_status==='uninterview'){
          return '待面试';
        }
      }

    },
    async fetchData() {
      this.loading = true;
      try {
        const applicationsResponse = await axios.get(`http://localhost:8080/applications/student/${this.studentId}`);
        const applications = applicationsResponse.data.data;

        const jobsResponse = await axios.get('http://localhost:8080/jobs');
        const jobs = jobsResponse.data.data;

        this.allApplications = applications;
        this.allJobs = jobs;

        const onlineTests = [];
        const results = [];

        for (const application of applications) {
          const job = jobs.find(job => job.job_id === application.job_id);

          const applicationData = {
            job_title: job?.job_title || '未知职位',
            job_description: job?.job_description || '无描述',
            applied_at: application.applied_at,
            application_status: application.application_status,
            application_id: application.application_id
          };

          if (application.application_status === 'uninterview' || application.application_status === 'shortlisted') {
            onlineTests.push(applicationData);
          } else {
            results.push(applicationData);
          }
        }

        this.onlineTests = onlineTests;
        this.results = results;
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    },
    async takeTest(test) {
      try {
        await axios.post(`http://localhost:8080/applications/${test.application_id}/register`);
        await this.fetchData()
        this.$message({
          message: `成功报名参加：${test.job_title}`,
          type: 'success'
        });
        this.updateApplicationStatus(test.application_id, 'interviewed');
      } catch (error) {
        console.error('报名失败:', error);
        this.$message.error('报名失败，请稍后再试');
      }
    },
    updateApplicationStatus(applicationId, newStatus) {
      const application = this.allApplications.find(app => app.application_id === applicationId);
      if (application) {
        application.application_status = newStatus;
      }
      this.loadResultsData();
    },
    loadResultsData() {
      const results = [];
      for (const application of this.allApplications) {
        const job = this.allJobs.find(job => job.job_id === application.job_id);
        if (application.application_status !== 'submitted' && application.application_status !== 'shortlisted') {
          results.push({
            job_title: job?.job_title || '未知职位',
            application_status: application.application_status,
            applied_at: application.applied_at
          });
        }
      }
      this.results = results;
    }
  }
};
</script>

<style>
body {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin: 0; /* 移除 body 的默认 margin */
}

.notification-page {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 0; /* 确保页面内容紧贴顶部 */
}

.page-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  max-width: 1400px;
  margin-top: 0; /* 确保表格容器紧贴顶部 */
}

.notification-table {
  width: 100%;
}

.el-table th, .el-table td {
  text-align: center;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.el-button {
  font-size: 14px;
}
</style>